#-*- coding:utf-8 -*-


def NW12(d, bdid):
    if d[0] != 0x68 or d[5] != 0x68:
        raise Exception('NW12 no 68')

    l = d[1] + (d[2] << 8) + 8
    if l > 4096 or len(d) < l:
        raise Exception('NW12 len')

    if d[l - 1] != 0x16:
        raise Exception('NW12 no 16')

    name = "%02X%02X%02X%02X%02X%02X-%d" % (d[9], d[8], d[7], d[12], d[11], d[10], bdid)
    return l, name

def GW3761(d, bdid):
    if d[0] != 0x68 or d[5] != 0x68:
        raise Exception('GW3761 no 68')
    
    l = ((d[1] + (d[2] << 8)) >> 2) + 8
    if l > 4096 or len(d) < l:
        raise  Exception('GW3761 len')

    if d[l - 1] != 0x16:
        raise Exception('GW3761 no 16')

    name = "%02X%02X%02X%02X-%d" % (d[8], d[7], d[10], d[9], bdid)
    return l, name

def OOP698(d, bdid):
    if d[0] != 0x68:
        raise Exception('OOP698 no 68')
    
    l = (d[1] + (d[2] << 8)) + 2
    if l > 4096 or len(d) < l:
        raise  Exception('OOP698 len')

    if d[l - 1] != 0x16:
        raise Exception('OOP698 no 16')

    name = "%02X%02X%02X%02X%02X%02X-%d" % (d[10], d[9], d[8], d[7], d[6], d[5], bdid)
    return l, name

def GW3761_698(d, bdid):
    try:
        l, name = GW3761(d, bdid)
    except:
        try:
            l, name = OOP698(d, bdid)
        except:
            raise Exception('GW3761_698 error')
        else:
            return l, name
    else:
        return l, name

def OOP698(d, bdid):
    if d[0] != 0x68:
        raise Exception('OOP698 no 68')
    
    l = (d[1] + (d[2] << 8)) + 2
    if l > 4096 or len(d) < l:
        raise  Exception('OOP698 len')

    if d[l - 1] != 0x16:
        raise Exception('OOP698 no 16')

    name = "%02X%02X%02X%02X%02X%02X-%d" % (d[10], d[9], d[8], d[7], d[6], d[5], bdid)
    return l, name

def PW101(d, bdid):
    if d[0] != 0x68:
        raise Exception('PW101 no 68')

    l = d[1] + 6
    name = "%02X%02X-%d" % (d[6], d[5], bdid)
    return l, name

def PW104(d, bdid):
    if d[0] != 0x68:
        raise Exception('PW104 no 68')

    l = d[1] + 2
    name = "%02X%02X-%d" % (d[11], d[10], bdid)
    return l, name

def I1(d, bdid):
    if d[0] != 0xA5 and d[1] != 0x5A:
        raise Exception('I1 no header')
    
    l = 27 + d[2] + d[3]*256
    name = d[4:21].decode() + "-%d" % bdid
    return l, name
